package com.karaoke.android.kege.vm

import com.karaoke.android.data.domain.QSong
import com.karaoke.android.kege.OnSearchTextChangedEvent
import com.karaoke.android.kege.SearchTypeChangedEvent
import com.trello.rxlifecycle.kotlin.bindToLifecycle
import org.simple.eventbus.EventBus
import org.simple.eventbus.Subscriber
import rx.Observable
import rx.Subscription
import java.util.concurrent.TimeUnit

/**
 * Created by allen on 2017/4/23.
 */
class SongSearchViewModel : BaseSongViewModel()
{
    override val emptyString: String? = "没有搜索到相关内容"
    override val errorString: String? = "搜索失败"


    init
    {
        EventBus.getDefault().register(this)
    }

    override fun onCreate()
    {
        super.onCreate()
        qSong.size = 40
        qSong.queryType = QSong.QueryType.QUERY_SEARCH
    }

    override fun onDestroy()
    {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }

    override fun onInitLoad()
    {
        super.onInitLoad()
        EventBus.getDefault().post(SearchTypeChangedEvent(qSong.keyword ?: ""))
        state?.showEmpty("输入歌曲首字母或名称")
    }


    private var searchSongSubscription: Subscription? = null

    @Subscriber
    fun onSearch(e: OnSearchTextChangedEvent)
    {
        qSong.keyword = e.text
        songs.clear()
        canLoadMore = false
        if (!e.text.isNullOrBlank())
        {
            searchSongSubscription?.unsubscribe()
            searchSongSubscription = Observable.just(onLoad()).delay(150, TimeUnit.MILLISECONDS).bindToLifecycle(this).subscribe()
        }
    }

}